package com.example.news.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.news.R;
import com.umeng.message.PushAgent;

public class WebActivity extends Activity {
    private WebView webView;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏系统自带的标题栏
        setContentView(R.layout.activity_web);

        PushAgent.getInstance(this).onAppStart();

        String url = getIntent().getStringExtra("url");
        String title = getIntent().getStringExtra("title");

        //找控件
        webView = (WebView) findViewById(R.id.news_web);
        TextView titles = (TextView) findViewById(R.id.web_title);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        titles.setText(title);//设置标题

        //记载地址
        webView.loadUrl(url);

        webView.setWebViewClient(new WebViewClient());

        //初始化WebView
        initSetting();

        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setVisibility(View.VISIBLE);
                // 设置进度
                progressBar.setProgress(newProgress);
                // 当进度==100的时候，让progressBar消失
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
    }
    /**
     * 初始化设置
     */
    private void initSetting() {
        WebSettings settings = webView.getSettings();
        //设置支持JavaScript脚步
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        //设置支持JavaScript
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setBuiltInZoomControls(true);
        settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
    }
    /*
     *  关闭当前页面
     */
    public void close(View v){
        finish();
    }
    // 监听返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 如果webView可以后退
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
            }
        }
        return true;
    }
}
